// {{ .Data.GenerateTitle }}
package main

import (
	_ "{{ .PkgName }}/repository"
	"gitee.com/kristas/booting-go/framework/core/bean"
	"gitee.com/kristas/booting-go/framework/core/statement/types"
	"gitee.com/kristas/booting-go/framework/data"
	"gitee.com/kristas/booting-go/gen_tool/booctl/creator"
	"gitee.com/kristas/booting-go/gen_tool/booctl/util"
	"os"
	"path/filepath"
	"sort"
)

type RepositoryGenerator struct {
	types.Component
	lock      *WdLock
	root      string
	Repos     []data.Repository `wire:""`
	beanNames []string
	layer     string
	cmd       util.GoCmd
}

func NewRepositoryGenerator(lock *WdLock) *RepositoryGenerator {
	return &RepositoryGenerator{lock: lock}
}

func (r *RepositoryGenerator) Init() error {
	r.root = r.lock.RequiredRoot()
	defer r.lock.Release()
	err := os.Chdir(r.root)
	if err != nil {
		return err
	}
	r.layer = "repository"
	for i := range r.Repos {
		repo := r.Repos[i]
		r.beanNames = append(r.beanNames, util.GetBeanStructName(repo))
	}
	sort.Slice(r.beanNames, func(i, j int) bool {
		return r.beanNames[i] < r.beanNames[j]
	})
	return r.Create()
}

func (r *RepositoryGenerator) Create() error {
	defer r.cmd.Fmt()
    g := creator.NewGoFile("common_factory", r.layer, r.layer+"_factory", false)
	g.SetAttribute("Beans", r.beanNames)
	g.SetAttribute("Package", r.layer)
	return g.Create()
}

func (r *RepositoryGenerator) Order() int {
	return 2
}

func (r *RepositoryGenerator) Async() bool {
	return true
}

func (r *RepositoryGenerator) Filter(bean bean.Bean) bool {
	_, ok := bean.(data.Repository)
	return ok
}

func (r *RepositoryGenerator) Do(bean bean.Bean) error {
	r.root = r.lock.RequiredRoot()
	defer r.lock.Release()
	repoFileName := filepath.Join(r.root, "repository", util.GetBeanFileName(bean))
	r.cmd.Fmt(repoFileName)
	return nil
}
